package com.oopnet.template.test.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者
 * 
 * @author mercy_yang
 *
 */
public class JMSProducer {

	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;

	private static final int SENDNUM = 10;

	public static void main(String[] args) {
		ConnectionFactory connectionFactory;// 连接工厂
		Connection connection = null;// 连接
		Session session = null; // 会话 接受或者发送消息的线程
		Destination destination; // 消息的目的地
		MessageProducer messageProducer; // 消息生产者

		connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);

		try {
			connection = connectionFactory.createConnection();
			connection.start(); // 启动连接
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); // 创建session

			destination = session.createQueue("FirstQueue1"); // 创建消息队列
			messageProducer = session.createProducer(destination); // 创建消息生产者
			sendMessage(session, messageProducer);
			session.commit();

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (session != null)
					session.close();
				if (connection != null)
					connection.close();
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
		for (int i = 0; i < JMSProducer.SENDNUM; i++) {
			TextMessage message = session.createTextMessage("ActiveMQ 发送消息" + i);
			System.out.println("发送消息： " + "ActiveMQ 发送的消息" + i);
			messageProducer.send(message);
		}
	}
}
